#include "soc_misc.h"
#include "soc_misc_impl.h"


static volatile uint32_t gTickMs = 0;
static uint32_t __Systemclock = 48000000;

void SOC_SetCpuFrequency(uint32_t freq)
{
    __Systemclock = freq;
}

uint32_t SOC_GetCpuFrequency()
{
  return __Systemclock;
}

void SOC_Delay(uint32_t ms)
{
  uint32_t startMs = SOC_GetCurrentMilliseconds();
  while (((uint32_t)(SOC_GetCurrentMilliseconds() - startMs)) < ms)
  {
    
  }
}

uint32_t SOC_GetCurrentMilliseconds()
{
  uint32_t val;
  
  // SOC_DisableAll_IT();
  val = gTickMs;
  // SOC_EnableAll_IT();
  return val;
}

void MiscIncTickMs(void) 
{
  gTickMs ++;
}

void BufferToHex(uint8_t b, uint8_t *out)
{
  static char *ntab = "0123456789ABCDEF";

  uint8_t h = b / 16;
  uint8_t l = b % 16;
  out[0] = ntab[h];
  out[1] = ntab[l];
}

//一般CPUID 是96bit [12 byte]
#define CPUID_BUF_MAX 30
static uint8_t cpuIDBuffer[CPUID_BUF_MAX + 1];

char* SOC_GetCPUID()
{
  static bool isInit = false;

  if(!isInit)
  {
    uint8_t i;
    uint8_t hexBuf[2];
    uint8_t index = 0;
    uint8_t len = SOC_GetCpuIdImpl(cpuIDBuffer + CPUID_BUF_MAX / 2);

    isInit = true;
    for(i = 0; i < len; i++)
    {
      BufferToHex(cpuIDBuffer[i + CPUID_BUF_MAX / 2], hexBuf);
      cpuIDBuffer[index++] = hexBuf[0];
      cpuIDBuffer[index++] = hexBuf[1];
    }

    cpuIDBuffer[index] = 0;
  }

  return (char*)cpuIDBuffer;
}

void SOC_CpuReset()
{

}
